package alexattar.gdxtest;

import java.util.HashMap;
import java.util.Map;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.Json.Serializable;
import com.badlogic.gdx.utils.OrderedMap;

public class Profile implements Serializable{

	private int currentLevelId;
	private int credits;
	private Map<Integer, Integer> highScores;
	private Ship ship;
	
	public Profile() {
		credits = 1000;
		highScores = new HashMap<Integer, Integer>();
		ship = new Ship();
		ship.install(ShipModel.USP_TALON);
		ship.install(FrontGun.PULSE_CANNON);
		ship.install(Shield.SIF);
	}
	
	public int getCurrentLevelId() {
		return currentLevelId;
	}
	
	public Map<Integer, Integer> getHighScores() {
		return highScores;
	}
	
	public int getHighScore(int levelId) {
		if (highScores == null) return 0;
		Integer highScore = highScores.get(levelId);
		return (highScore == null ? 0 : highScore);
	}
	
	public boolean notifyScore(int levelId, int score) {
		if (score > getHighScore(levelId)) {
			highScores.put(levelId, score);
			return true;
		}
		return false;
	}
	
	public int getCredits() {
		return credits;
	}
	
	public Ship getShip() {
		return ship;
	}
	
	public boolean canBuy(Item item) {
		if (ship.contains(item)) {
			return false;
		}
		if (item.getPrice() > credits) {
			return false;
		}
		return true;
	}
	
	public boolean buy(Item item) {
		if (canBuy(item)) {
			Gdx.app.log(GdxTestGame.LOG, "Buying item: " + item);
			ship.install(item);
			credits -= item.getPrice();
			Gdx.app.log(GdxTestGame.LOG, "Credits abailable: " + credits);
			return true;
		}
		else {
			Gdx.app.log(GdxTestGame.LOG, "Insufficient credits to buy item: " + item);
			return false;
		}
	}
	
	@Override
	public void write(Json json) {
		json.writeValue("currentLevelId", currentLevelId);
		json.writeValue("credits", credits);
		json.writeValue("highScores", highScores);
		json.writeValue("ship", ship);
	}

	@SuppressWarnings("unchecked")
	@Override
	public void read(Json json, OrderedMap<String, Object> jsonData) {
		currentLevelId = json.readValue("currentLevelId", Integer.class, jsonData);
		credits = json.readValue("credits", Integer.class, jsonData);
		
		Map<String, Integer> highScores = json.readValue("highScores", HashMap.class, Integer.class, jsonData);
		for(String levelIdAsString : highScores.keySet()) {
			int levelId = Integer.valueOf(levelIdAsString);
			Integer highScore = highScores.get(levelIdAsString);
			this.highScores.put(levelId, highScore);
		}
		
		ship = json.readValue("ship", Ship.class, jsonData);
	}

}
